package processor

import (
	"encoding/json"
	"errors"
	"fmt"
	"net"
	"study/14_practice_chat/common"
	"study/14_practice_chat/utils"
)

/*
用户的处理器
*/

type ClientUserProcessor struct {
	Conn net.Conn
}

// 实现接口方法
// 1. 创建request的消息发送给服务端
// 2. 服务服务端消息并解析
func (this *ClientUserProcessor) Login(name string, password string) (err error) {
	logInMessage := common.LogInMessage{
		Name:     name,
		Password: password,
	}
	var jsonBytes []byte
	jsonBytes, err = json.Marshal(logInMessage)
	if err != nil {
		fmt.Println("serialized LogInMessage err = ", err)
		return
	}
	request := common.RequestBody{
		DataType: common.Type_LogInMessage,
		Data:     string(jsonBytes),
	}
	err = utils.WriteRequest(this.Conn, request)
	if err != nil {
		fmt.Println("send request err = ", err)
		return
	}
	// 获得响应，判断是否登陆成功！
	var response common.ResponseBody
	response, err = utils.ReadResponse(this.Conn)
	if err != nil {
		fmt.Println("login response error : ", err)
		return
	}
	if response.Code == 200 {
		if "ok" == response.Msg {
			fmt.Println("log in success!")
			return nil
		} else {
			fmt.Printf("response failure , code = %v, msg = %v \n", response.Code, response.Msg)
			err = errors.New(response.Msg)
			return
		}
	} else {
		fmt.Printf("response failure , code = %v, msg = %v \n", response.Code, response.Msg)
		err = errors.New(response.Msg)
		return
	}
}
